package com.ruoyi.common.utils.file;

import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.helpentity.MockMultipartFile;
import com.ruoyi.common.utils.StringUtils;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.UUID;

/**
 * 图片处理工具类
 *
 * @author ruoyi
 */
public class ImageUtils {
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

    public static byte[] getImage(String imagePath) {
        InputStream is = getFile(imagePath);
        try {
            return IOUtils.toByteArray(is);
        } catch (Exception e) {
            log.error("图片加载异常 {}", e);
            return null;
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    public static InputStream getFile(String imagePath) {
        try {
            byte[] result = readFile(imagePath);
            result = Arrays.copyOf(result, result.length);
            return new ByteArrayInputStream(result);
        } catch (Exception e) {
            log.error("获取图片异常 {}", e);
        }
        return null;
    }

    /**
     * 读取文件为字节数据
     *
     * @param url 地址
     * @return 字节数据
     */
    public static byte[] readFile(String url) {
        InputStream in = null;
        try {
            if (url.startsWith("http")) {
                // 网络地址
                URL urlObj = new URL(url);
                URLConnection urlConnection = urlObj.openConnection();
                urlConnection.setConnectTimeout(30 * 1000);
                urlConnection.setReadTimeout(60 * 1000);
                urlConnection.setDoInput(true);
                in = urlConnection.getInputStream();
            } else {
                // 本机地址
                String localPath = RuoYiConfig.getProfile();
                String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
                in = new FileInputStream(downloadPath);
            }
            return IOUtils.toByteArray(in);
        } catch (Exception e) {
            log.error("获取文件路径异常 {}", e);
            return null;
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    /**
     * 判断文件是否为图片
     */
    public static boolean isPicture(String imgName) {
        boolean flag = false;
        if (StringUtils.isBlank(imgName)) {
            return false;
        }
        String[] arr = {"bmp", "dib", "gif", "jfif", "jpe", "jpeg", "jpg", "png", "tif", "tiff", "ico"};
        for (String item : arr) {
            if (item.equals(imgName)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 压缩图片
     * @param file
     * @return
     * @throws IOException
     */
    public static MultipartFile thumbnailsPic(MultipartFile file) throws IOException {
        // 获取到上传的文件名
        String fileName = file.getOriginalFilename();
        String nameNotSuffix = FileUtils.getNameNotSuffix(fileName);
        String suffix = FileUtils.getNameSuffix(fileName);
        String newFileName = nameNotSuffix + FileUtils.THUMBN + "." + suffix;
        // UUID 作为文件名
        String uuid = String.valueOf(UUID.randomUUID());
        // 在项目根目录下的 upload 目录中生成临时文件
        File directory = new File("");// 参数为空
        String courseFile = directory.getCanonicalPath();
        String upload = courseFile + "/upload";
        String tmpFilePath = upload + "/" + uuid + "." + suffix;
        File newFile = FileUtil.touch(tmpFilePath);
        // 压缩到500kb
        byte[] bytes = ThumbnailsUtils.compressPicForScaleToBytes(file.getBytes(), 500, fileName);
        FileUtil.writeBytes(bytes, newFile);
        try (
                // 获取输入流
                FileInputStream input = new FileInputStream(newFile);
        ) {
            // 转为 MultipartFile
            MultipartFile multipartFile = new MockMultipartFile("file", newFileName, "text/plain", input);
            newFile.delete();
            return multipartFile;
        }
    }
}
